<template>
  <div id="ForeBlog" style="background: #f4f5f5">
   <div style="width: 160vh;margin:0 auto;background: #f4f5f5">
     <el-container>
       <el-main >
         <div class="person-main">
            <div class="person-main-title" v-text="blogObject.title"></div>
            <div class="person-main-content">
              <div class="person-main-content1" v-html="blogObject.content" ></div>
              <div class="person-main-content-bottom">
                <span>分类：</span>
                <span>{{ blogObject.tag }}</span>
                <span>标签：</span>
                <span>{{ blogObject.flag }}</span>
              </div>
            </div>
            <div class="person-main-comment">
              <div class="comment-edit">
<!--                66666-->
                <el-icon><UserFilled /></el-icon>
                <textarea name="" id="" cols="30" rows="10" :placeholder="foreBlogPlaceHolder" v-model="blogCommentContent" @click="clickBlogComment"/>
                <span>
<!--                  <svg class="icon" width="50" height="50" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" data-v-042ca774="" >-->
<!--                    <path fill="currentColor" d="M64 448l832-320-128 704-446.08-243.328L832 192 242.816 545.472 64 448zm256 512V657.024L512 768 320 960z">-->
<!--                    </path>-->
<!--                  </svg>-->
                  <el-icon><Promotion @click="sendComment" /></el-icon>
                </span>
              </div>
              <div class="comment-all-count" ref="foreBlogAllComment">
                全部评论 &nbsp; {{ commentCount }}
                <div >
<!--                  <el-switch-->
<!--                      v-model="switchHot"-->
<!--                      inline-prompt-->
<!--                      style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"-->
<!--                      size="large"-->
<!--                      active-text="最新"-->
<!--                      inactive-text="最热"-->
<!--                  />-->
                </div>
              </div>

              <CommentCom :blogComment="blogComment" ref="commentWrap"></CommentCom>
            </div>
         </div>
       </el-main>

       <!-- 个人信息区 -->
       <el-aside width="20vw">
         <div class="person-aside">
           <div>
             <el-avatar :size="100" fit="cover"
                        :src="blogPerson.avatar"/>
             <span v-text="blogPerson.username"></span>
           </div>
           <div>
             <div>园龄</div>
             <div></div>
           </div>
           <div>
             <div>粉丝</div>
             <div></div>
           </div>
           <div>
             <div>关注</div>
             <div></div>
           </div>
           <div>
             <el-button :type="getConcernTypeStyle(concernType)" @click="changeConcernType()">关注</el-button>
             <el-button type="primary" plain :disabled="!concernType" @click="routerToChat">私信</el-button>
           </div>
         </div>

       </el-aside>

       <!--     左边panel面板-->
       <ul class="foreBlog-left-panel">
<!--         点赞-->
         <li @click="likeCountChange">
           <el-badge :value="blogObject.likesCount" class="item">
               <el-icon :color="likeColor"><Pointer /></el-icon>
           </el-badge>
         </li>
<!--         评论-->
         <li @click="badgeCommentClick($event)">
           <el-badge :value="0" class="item">
             <el-icon color="#8a919f"><ChatDotSquare /></el-icon>
           </el-badge>
         </li>
<!--         收藏-->
         <li @click="collectionCountChange">
           <el-badge :value="blogObject.collectionCount" class="item">
             <el-icon :color="colColor"><StarFilled /></el-icon>
           </el-badge>
         </li>
<!--         分享-->
         <li>
           <el-dropdown size="large" type="primary" placement="right" popper-class="foreBlog-el-dropdown-0">
             <el-icon color="#8a919f"><Share /></el-icon>
             <template #dropdown>
               <el-dropdown-menu>
                 <el-dropdown-item v-if="checkCurUserBoolean">
                   <div class="block" @click="showForeBlogDrawer()">
                     <el-icon color="#8a919f"><Plus /></el-icon>标签
                   </div>
                 </el-dropdown-item>
<!--                 <el-dropdown-item>Action 2</el-dropdown-item>-->
<!--                 <el-dropdown-item>Action 3</el-dropdown-item>-->
<!--                 <el-dropdown-item>Action 4</el-dropdown-item>-->
               </el-dropdown-menu>
             </template>
           </el-dropdown>
         </li>
         <li ></li>
<!--         举报-->
<!--         <li><el-icon color="#8a919f"><Opportunity /></el-icon></li>-->
<!--&lt;!&ndash;         沉浸阅读&ndash;&gt;-->
<!--         <li><el-icon color="#8a919f"><FullScreen /></el-icon></li>-->
       </ul>
     </el-container>

<!--     Drawer 抽屉-->
     <el-drawer v-model="foreBlogDrawer" title="标签列表" :with-header="false">
       <div class="fore-blog-drawer" v-for="(item,index) in tagList">
         <el-button round size="large" plain v-if="!showTagIcon(item)" @click="changeTag(item,1)">
           <el-icon color="#8a919f" ><Plus /></el-icon>
         </el-button>
         <el-button round  size="large" plain v-else @click="changeTag(item,0)">
           <el-icon color="#8a919f" ><Minus/></el-icon>
         </el-button>
         {{ item }}
       </div>
       <div class="fore-blog-drawer" >
         <el-button round size="large" plain @click="addTag()">
           <el-icon color="#8a919f" ><Plus /></el-icon>
         </el-button>
         <el-input v-model="inputTag" placeholder="自定义标签" />
       </div>
       <div >
         <el-button type="primary" plain @click="saveTag">保存</el-button>
<!--         <el-button type="danger" plain>Danger</el-button>-->
       </div>
     </el-drawer>

<!--     回到顶部-->
     <el-backtop :right="30" :bottom="100" :visibility-height="100">
       <el-icon size="30"><Top /></el-icon>
     </el-backtop>

   </div>
  </div>
</template>

<script>
// import {Position,UserFilled,Promotion} from "@element-plus/icons-vue"
import ForeHead from "@/components/ForeHead";
import request from "@/utils/request";
import { ElMessageBox, ElMessage } from 'element-plus'
import CommentCom from "@/components/blog/CommentCom";
import { Position,UserFilled,Promotion,Pointer,
  ChatDotSquare,StarFilled,Share,Opportunity,
  FullScreen,Plus,Minus,Top} from '@element-plus/icons'
import {likeCountChange,colCountChange} from "@/api/blog/blog";
import {fetchTagList,save} from "@/api/blog/tag";
import {concern} from "../../api/blog/user";
import {mapState, mapGetters, mapActions, mapMutations} from "vuex";
import {getUserName,getUserId} from '@/utils/auth'
import {debounce} from "../../utils";

export default {
  name: "ForeBlog",

  provide(){
    return{
      foreBlogLoad:this.load
    }
  },

  components:{
    CommentCom, ElMessage, Position, UserFilled, Promotion, Pointer,
    ChatDotSquare, StarFilled, Share, Opportunity, FullScreen, Plus,
    Minus, Top,
  },

  watch:{
    isLogin(newVal,oldVal){
      console.log("isLogin",newVal,oldVal);
      // this.changeConcernType();
      this.load();
    }
  },

  computed:{
    ...mapState('user',['isLogin']),
    foreBlogPlaceHolder(){
      // console.log("====this.curUser=======",this.curUser)
      if(this.curUser && this.curUser != ''){
        return '看完啦，分享一下感受吧~'
      }else {
        return '看完啦，登录分享一下感受吧~'
      }
    },
    likeColor(){
      return this.blogObject.likeBoolean?'#0016f4':'#8a919f';
    },
    colColor(){
      return this.blogObject.collectionBoolean?'#0016f4':'#8a919f';
    },
  },

  data(){
    return{
      blogObject:{},
      blogPerson:{},
      blogComment:[],
      blogCommentContent:'',
      curUser:'',
      curUserId:'',
      messagePageNum:0,
      messagePageSize:10,
      commentCount:54,
      switchHot:true,
      foreBlogDrawer:false,
      tagList:[],
      curTagList:[],
      changeTagList:[],
      inputTag:'',
      checkCurUserBoolean:false,
      concernType:false,
    }
  },

  created() {
    // this.curUser = sessionStorage.getItem("user")?JSON.parse(sessionStorage.getItem("user")):'',
    // this.curUserId = sessionStorage.getItem("userId")?JSON.parse(sessionStorage.getItem("userId")):'',
    // this.load();
  },

  mounted(){
    let self = this;
    window.addEventListener("scroll", this.handleScroll.bind(this,self), true);
    this.curUser = getUserName()
    this.curUserId = getUserId()
    this.load();
  },
  beforeDestroy(){
    let self = this
    window.removeEventListener("scroll", this.handleScroll.bind(this,self), true);
  },

  methods:{
    ...mapMutations("app",['OPEN_LOGIN']),
    commentDelete(commentId){
       ElMessageBox.confirm(
        '确认删除?',
        'Warning',
        {
          confirmButtonText: 'OK',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
          request.delete("/fore/comment/delete",{
            params:{
              id:commentId
            }
          }).then(res=>{
            if(res.code == 200 || res.code == 0){
              this.load()
            }
          })
      })
    },

    clickBlogComment(){
      let user = sessionStorage.getItem("user")
      // if(!user) this.$router.push("/login")
      if(!user) this.OPEN_LOGIN();
    },

    sendComment(){
      // debugger
      let user = sessionStorage.getItem("user")
      // if(!user) this.$router.push("/login")
      if(!user) this.OPEN_LOGIN();

      let userSeeion = sessionStorage.getItem("user")
      // debugger
      if(!userSeeion || userSeeion == null){
        ElMessage({
          message: "请先登录！",
          type:'warning'
        })
      }else{
        // axios请求保存评论
        if(this.blogCommentContent == null || this.blogCommentContent == '' ){
          ElMessage({
              type: "warning",
              message: "请输入评论！"
            })
        }else{
           userSeeion = JSON.parse(userSeeion)
        request.post("/fore/comment/save",{
            content:this.blogCommentContent,
            blogId:this.$route.params.id,
            username:userSeeion
        }).then((res)=>{
          if(res.code == 200 || res.code == 0){
            this.blogCommentContent = ''
            this.load()
          }
        })
        }

      }

    },

    load(){
      request.get("/fore/blog/" + this.$route.params.id).then(res => {
        this.blogObject = res.data
        this.blogPerson = res.data.user
        this.curTagList = (res.data.tagList == null || res.data.tagList == undefined) ?[]:res.data.tagList
        this.checkCurUserBoolean = this.checkCurUser()
        this.getConcernType(this.blogObject.concernType);
        // console.log("blogObject.likeBooleann == true",this.blogObject.likeBooleann)
      })

      this.getComment();

    },

    getComment(){
      request.get("/fore/comment/" + this.$route.params.id,{
        params:{
          pageNum: this.messagePageNum,
          pageSize: this.messagePageSize
        }
      }).then((res)=>{
        this.blogComment = res.data
      })
    },

    likeCountChange(){
      likeCountChange({
        blogId:this.blogObject.id,
        count:this.blogObject.likesCount,
        userId:this.blogObject.userId
      }).then((res)=>{
        if(res.code == 0){
          this.load()
        }else {
            ElMessage({
                type: "warning",
                message: res.msg
            })
        }
      })
    },
    collectionCountChange(){
      colCountChange({
        blogId:this.blogObject.id,
        count:this.blogObject.collectionCount,
        userId:this.blogObject.userId
      }).then((res)=>{
        if(res.code == 0){
          this.load()
        }else {
            ElMessage({
                type: "warning",
                message: res.msg
            })
        }
      })
    },
    showDropdown0Click(){
      // this.$refs.foreBlogdropdown0.visible = true
    },

    showForeBlogDrawer(){
      fetchTagList().then((res)=>{
        this.tagList = res.data
        console.log(" this.tagList", this.tagList)
      })
      this.foreBlogDrawer = true
    },

    /* 0-减少;1-新增 */
    changeTag(item,changeBoolean){
      // console.log("item",item)
      // console.log("changeBoolean",changeBoolean)
      if(changeBoolean == 0){
        this.curTagList = this.curTagList.filter(tag=>tag != item)
      }
      if(changeBoolean == 1){
        // this.tagList.push(item)
        console.log("this.curTagList",this.curTagList)
        this.curTagList.push(item)
      }

      // console.log("curTagList",this.curTagList)
    },
    addTag(item){
      if(this.inputTag == ''){
        return
      }
      this.tagList.push(this.inputTag)
      this.curTagList.push(this.inputTag)
      this.inputTag = ''
    },
    showTagIcon(item){
        // console.log(val);//根据val进行操作
        // console.log("this.curTagList.includes(item)",this.curTagList.includes(item));
      if(this.curTagList == null || this.curTagList == []){
        return false
      }
      return this.curTagList.includes(item);
    },
    saveTag(){
      save({
        tagList:this.curTagList,
        blogId:this.blogObject.id
      }).then((res)=>{
        if(res.code == 0){
          this.load()
        }
      })
    },
    checkCurUser(){
      if(!this.curUser && this.curUser == ''){
        return  false
      }
      // console.log("this.blogObject.user.username",this.blogObject.user.username)
      // console.log("this.curUser",this.curUser)
      // console.log("this.blogObject.userId == this.curUser",this.blogObject.user.username == this.curUser)
      return this.blogObject.user.username == this.curUser
    },
    badgeCommentClick(event){
      // console.log("event",event)
/*      vue锚点连接跳转*/
      this.$refs.foreBlogAllComment.scrollIntoView({
        block: 'start',
        behavior: 'smooth'
      })
    },
    changeConcernType(val){
      if(!getUserName()){
        this.OPEN_LOGIN();
        return ;
      }
      let data = {
        userId:this.curUserId,
        followUserId:this.blogObject.user.id
      }
      concern(data).then((res)=>{
        if(res.code == 0){
          this.concernType = res.data;
          this.load();
        }
      });
    },
    getConcernType(type){
      if(!getUserName()){
        this.concernType = false;
        return ;
      }
      this.concernType = type;
    },
    getConcernTypeStyle(concernType){
      return concernType?"info":"primary";
    },
    routerToChat(){
      this.$router.push({
        name:"ChatRoom",
        params:{
          username:this.blogObject.user.username
        },
        state:{
          username:this.blogObject.user.username
        },
      });
    },
    handleScroll:debounce((self)=>{
      //1.获取滚动区域元素
      let commentWrap = self.$refs.commentWrap;
      console.log("commentWrap",commentWrap);
      let body = document.body  // 获取滚动条的dom
      console.log("commentWrap触发滑动");
      if (commentWrap) {
        //2.获取元素高度
        let height = commentWrap.$el.offsetHeight;
        //3.获取滚动区域到头部的距离
        let top = commentWrap.$el.scrollTop || document.documentElement.scrollTop;
        //4.获取滚动条高度
        // let scrollHeight = commentWrap.$el.scrollHeight;
        let scrollHeight = document.body.scrollHeight;
        console.log("height",height,"top",top,"scrollHeight",scrollHeight)
        //5.滚动条到底部的条件 (滚动区域到头部的距离 + 屏幕高度 = 可滚动的总高度)
        if (
            (top + height + 1 >= scrollHeight) &&
            (self.messagePageNum * self.messagePageSize <= self.blogComment.length)
        ) {
          self.messagePageSize += 10;
          self.getComment();
        }
      }
    },200),
  }
}
</script>

<style lang="less" scoped>
@import url('../../style/ForeBlog.less');
</style>
